package com.whisperly.echotalk.starryb.utils;

import android.content.Context;
import android.view.View;

import com.google.android.material.snackbar.Snackbar;
import com.whisperly.echotalk.starryb.R;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendGmail {
    private static long verificationCodeTime = 0;
    private static String verificationCode = "";
    private static final String SYMBOLS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static void gmailssl(Properties props) {
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
    }
 

    private static void gmailtls(Properties props) {
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
    }


    public static void generateCode() {
        Random random = new Random();
        char[] nonceChars = new char[5];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(random.nextInt(SYMBOLS.length()));
        }
        verificationCode = new String(nonceChars);
        verificationCodeTime = System.currentTimeMillis();
    }

    public static boolean isCodeValid() {

        long fiveMinutesInMillis = 5 * 60 * 1000;

        return (System.currentTimeMillis() - verificationCodeTime) <= fiveMinutesInMillis;
    }

    public static void gmailSender(String email, View view, Context context) {
        System.out.println("Message sent start.");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Properties props = new Properties();
                //选择ssl方式
                gmailssl(props);

                final String username = "xchen6367@gmail.com";//gmail邮箱
                final String password = "hplquaibuaigxejo";//密码
                Session session = Session.getInstance(props,
                        new Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                            }
                        });
                try {
                    MimeMessage msg = new MimeMessage(session);
                    String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()).format(new Date());
                    msg.setFrom(new InternetAddress(username, "Blink Chat", "UTF-8"));
                    msg.setRecipients(Message.RecipientType.TO, email);
                    msg.setSubject("This email is for verifying your account");
                    msg.setSentDate(new Date());
                    msg.setContent("<h3>\n" +
                            "\t<span style=\"font-size:16px;\">亲爱的用户：</span> \n" +
                            "</h3>\n" +
                            "<p>\n" +
                            "\t<span style=\"font-size:14px;\">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style=\"font-size:14px;\">&nbsp; <span style=\"font-size:16px;\">&nbsp;&nbsp;您好！您正在进行邮箱验证，本次请求的验证码为：<span style=\"font-size:24px;color:#FFE500;\"> "+verificationCode+"</span>,本验证码5分钟内有效，请在5分钟内完成验证。（请勿泄露此验证码）如非本人操作，请忽略该邮件。(这是一封自动发送的邮件，请不要直接回复）</span></span>\n" +
                            "</p>\n" +
                            "<p style=\"text-align:right;\">\n" +
                            "\t<span style=\"background-color:#FFFFFF;font-size:16px;color:#000000;\"><span style=\"color:#000000;font-size:16px;background-color:#FFFFFF;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;background-color:#FFFFFF;\">Blink Chat</span></span></span> \n" +
                            "</p>\n" +
                            "<p style=\"text-align:right;\">\n" +
                            "\t<span style=\"background-color:#FFFFFF;font-size:14px;\"><span style=\"color:#FF9900;font-size:18px;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;\"><span style=\"font-size:16px;color:#000000;background-color:#FFFFFF;\">"+time+"</span><span style=\"font-size:18px;color:#000000;background-color:#FFFFFF;\"></span></span></span></span> \n" +
                            "</p>","text/html;charset=UTF-8");
                    Transport.send(msg);
                    System.out.println("Message sent.");
                    showSnackBar("blue", view, "The verification code has been sent to your email!", context);
                } catch (Exception e) {
                    showSnackBar("red", view, "Failed to send email!", context);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void showSnackBar(String type, View view, String content, Context context) {
        if (type.contentEquals("blue")) {
            Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_SHORT);
            snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.colorBlue));
            snackbar.show();
        } else if (type.contentEquals("red")) {
            Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_SHORT);
            snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.colorRed));
            snackbar.show();
        } else if (type.contentEquals("yellow")) {
            Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_SHORT);
            snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.colorGold));
            snackbar.show();
        }
    }

    public static String getVerificationCode() {
        return verificationCode;
    }

    public static void setVerificationCode(String verificationCode) {
        SendGmail.verificationCode = verificationCode;
    }
}